package com.hl.card.modular.pack.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hl.card.common.persistence.model.DisMemberInfo;
import com.hl.card.common.persistence.model.User;
import com.hl.card.common.remote.user.RemoteUser;
import com.hl.card.common.remote.user.RemoteUserService;
import com.hl.card.core.shiro.ShiroKit;
import com.hl.card.modular.pack.dto.AwardUser;
import com.hl.card.modular.pack.service.DisMemberInfoService;
import com.hl.card.modular.pack.service.RewardLogin;
import com.hl.card.modular.pack.service.UserDataService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/api/init")
public class InitializeController {
    private static final Logger logger = LoggerFactory.getLogger(UserDataController.class);
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private UserDataService userDataService;

    @Autowired
    private DisMemberInfoService disMemberInfoService;

    @Autowired
    private RewardLogin rewardLogin;

    @RequestMapping
    public Object init(HttpServletRequest request, HttpServletResponse response) {
        String salt= ShiroKit.getRandomSalt(5);
        System.out.println("初始化卡包用户");
        AwardUser rewardDto=new AwardUser();
        rewardDto.setRegDate(new Date());

        DisMemberInfo disMemberInfo = null;//合伙人
        User cardUser = null;//卡包用户
        String regCode = null;
        String referRegCode = null;
        RemoteUser remoteUser = null;
        String recommendCode = "";
        Map<String, String> map = new HashMap();
        String token = request.getParameter("token");
        String userid = request.getParameter("userid");
        String parent_regcode = request.getParameter("parentRegCode");
        rewardDto.setRegCode(parent_regcode);
        rewardDto.setUserId(userid);

        if (StringUtils.isBlank(token)) {
            map.put("code", "0");
            map.put("msg", "token非法");
            return map;
        }
        if (StringUtils.isBlank(userid)) {
            map.put("code", "0");
            map.put("msg", "userid 不正确");
            return map;
        }
        Boolean b = userDataService.checkToken(token);
        try {
            if (!b) {
                map.put("code", "0");
                map.put("msg", "token非法");
            } else {
                JSONObject json = remoteUserService.findSsoUserByUserId(userid);
                if (json.get("code").equals("0")) {
                    JSONObject userObj = (JSONObject) json.get("user");
                    remoteUser = JSON.parseObject(userObj.toJSONString(), RemoteUser.class);
                    rewardDto.setRegDate(remoteUser.getCreateTime());
                }
                cardUser = userDataService.checkAndSaveUser(userid);
                if (null == cardUser) {//如果此用户id没有卡包用户，创建卡包用户
                    logger.info("/api/init: 创建卡包新用户");
                    cardUser = new User();
                    cardUser = userDataService.ssouserToCarPackUser(remoteUser, cardUser);
                    if (StringUtils.isNotEmpty(parent_regcode)) {
                        cardUser.setRefer_reg_code(parent_regcode);
                    }
                    cardUser.setSalt(salt);
                    userDataService.insert(cardUser);
//                    referRegCode = cardUser.getRefer_reg_code();
                    //loginUserService.reward(rewardDto);
                    System.out.println("开始发放注册用户奖励");
                    rewardLogin.reward(JSON.toJSONString(rewardDto));
                }
                regCode = cardUser.getReg_code();
//                referRegCode = cardUser.getRefer_reg_code();
//                Cookie cookie = new Cookie("regCode", regCode);
//                response.addCookie(cookie);
//                if (referRegCode != null) {
//                    Cookie cookie1 = new Cookie("referRegCode", referRegCode);
//                    response.addCookie(cookie1);
//                }

                disMemberInfo = disMemberInfoService.selectDisMemberInfo(cardUser.getUserId(), null);

                if (null != disMemberInfo) {
                    recommendCode = disMemberInfo.getDis_recommendation_no();
                    recommendCode=StringUtils.isBlank(recommendCode)?"":recommendCode;
                }
                map.put("recommendCode", recommendCode);
                map.put("regCode", regCode);
                map.put("code", "1");
                map.put("msg", "初始化成功");
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            map.put("code", "0");
            map.put("msg", "系统异常！");
        }
        return map;
    }
}
